package com.etown.action;

import java.io.UnsupportedEncodingException;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.etown.dao.CommonDAO;
import com.etown.util.SqlMgr;
import com.etown.util.StringUtil;

/**
 * 论坛
 * @author 大漠
 * 
 */
public class ForumAction extends BaseAction {
	private int postType;
	
	private String blockId;		//版块ID

	private String postTitle;	//帖子标题

	private String content;		//帖子内容
	
	private String postId;		//帖子ID
	
	private String parentId;	//父帖ID
	
	private int totalPages;		//分页用：总页数
	
	private int pageIndex=1;	//分页用：当前显示的页码
	
	private int postPerPage=30;	//每页显示的条数，默认为30
	
	/**
	 * 加载最新30帖
	 * 带分页，默认取0到30条
	 * 注意：此方法是进入论坛版块时的入口
	 * @return
	 */
	public String loadPosts30(){
		//论坛左侧的版块树只生成一次，存入Session
		String treeStr=(String) getSessionAttr("fTree");
		if(treeStr==null){
			treeStr=generateBlockTree();
			this.setSessionAttr("fTree",treeStr);
		}
		
		//josn形式的论坛版块数据
		if(getSessionAttr("rootBlocks")==null){
			this.getForumBlocks();
		}
		
		//取指定板块的最新30帖，带分页，根据页码pageIndex和每页帖子数postPerPage计算
		int start=(pageIndex-1)*postPerPage;
		int end=pageIndex*postPerPage;
		JSONArray arr=CommonDAO.getList(SqlMgr.getSql("GET_30_POSTS"),blockId,blockId,blockId,start,end);
		this.setReqAttr("posts30",arr.toString());
		this.setSessionAttr("blockId", blockId);
		
		//取当前版块的总页数
		JSONObject obj=CommonDAO.getSingle(SqlMgr.getSql("GET_POST_COUNT"), this.blockId);
		if(obj!=null){
			String temp=obj.getString("total");
			if(!StringUtil.isEmpty(temp)){
				this.totalPages=(int) Math.ceil(Float.parseFloat(temp)/postPerPage);
				this.setReqAttr("totalPages", totalPages);
			}
		}
		return "success";
	}

	/**
	 * 读取帖子内容
	 * @return
	 */
	public String readPost(){
		//读取主帖和跟帖，包括每个帖子对应的用户信息；每页20条，postId为主帖ID，每页显示20个帖子
		int ct=20;
		int start=(pageIndex-1)*ct;
		int end=pageIndex*ct;
		JSONArray arr=CommonDAO.getList(SqlMgr.getSql("READ_POST"),postId,postId,start,end);
		System.out.println(arr.toString());
		
		//获取跟帖总页数
		JSONObject obj=CommonDAO.getSingle(SqlMgr.getSql("GET_COMMENT_COUNT"),postId,postId);
		if(obj!=null){
			String temp=obj.getString("total");
			if(!StringUtil.isEmpty(temp)){
				this.totalPages=(int) Math.ceil(Float.parseFloat(temp)/ct);
				this.setReqAttr("totalPages", totalPages);
			}
		}
		
		//阅读数+1
		CommonDAO.update(SqlMgr.getSql("READ_PLUS"), postId);
		//主帖用户金币数增加0.01
		CommonDAO.update(SqlMgr.getSql("ADD_USER_MONEY"),0.01,getSessionAttr("userName"));
		
		this.setReqAttr("posts",arr.toString());
		return "success";
	}
	
	/**
	 * 发新帖
	 * @return
	 */
	public String addNewPost() {
		String userName=(String) this.getSessionAttr("userName");
//		for(int i=0;i<30;i++){
			//插数据表
			CommonDAO.update(SqlMgr.getSql("ADD_NEW_POST"), userName,postTitle,content,blockId,"");
			//用户金币数增加
			CommonDAO.update(SqlMgr.getSql("ADD_USER_MONEY"),30,getSessionAttr("userName"));
//		}
		return "success";
	}
	
	/**
	 * 删除帖子
	 * @return
	 */
	public String delPost(){
		//如果删除的是主帖，所有跟帖删除，跳转到论坛对应版块的首页
		CommonDAO.update(SqlMgr.getSql("DEL_POST"), postId,postId);
		//如果删除的是跟帖，刷新读帖页面
		if(parentId.equals("0")){
			return "toMain";
		}else{
			return "toPost";
		}
	}
	
	/**
	 * 跟帖啊
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	public String commentPost() throws UnsupportedEncodingException{
		String userName=(String) this.getSessionAttr("userName");
		//插数据表
		CommonDAO.update(SqlMgr.getSql("ADD_COMMENT_POST"), userName,content,0,0,"",parentId);
		//跟帖数+1，更新最新回复时间
		CommonDAO.update(SqlMgr.getSql("COMMENT_PLUS"), parentId);
		//主帖用户金币数增加0.05
		CommonDAO.update(SqlMgr.getSql("ADD_USER_MONEY"),0.01,getSessionAttr("userName"));
		return "success";
	}
	
	/**
	 * 生成论坛左侧树
	 * 手动拼接HTML
	 * @return
	 */
	private String generateBlockTree(){
		StringBuffer result=new StringBuffer();
		result.append("<ul id='navigation'>");//注意：此ID和页面脚本绑定，不要更改
		JSONArray roots=CommonDAO.getList(SqlMgr.getSql("GET_FORUM_CHILD_BLOCK"),0);
		if(roots!=null){
			for(int i=0;i<roots.size();i++){
				JSONObject jsonObj=roots.getJSONObject(i);
				String bId=jsonObj.getString("block_id");
				String link=jsonObj.getString("link");
				if(i==0){
					this.blockId=jsonObj.getString("block_id");
				}
				if(link.equals("1")){
					result.append("<li><a id='"+bId+"' href='loadPosts30.action?blockId="+bId+"'>");
				}else{
					result.append("<li><a id='"+bId+"' href='#'>");
				}
				
				result.append(jsonObj.get("block_name"));
				result.append("</a>");
				String blockId=jsonObj.getString("block_id");
				
				JSONArray children=CommonDAO.getList(SqlMgr.getSql("GET_FORUM_CHILD_BLOCK"), blockId);
				if(children!=null&&children.size()!=0){
					result.append("<ul>");
					for(int j=0;j<children.size();j++){
						JSONObject child=children.getJSONObject(j);
						bId=child.getString("block_id");
						link=child.getString("link");
						if(link.equals("1")){
							result.append("<li><a id='"+bId+"' href='loadPosts30.action?blockId="+bId+"'>");
						}else{
							result.append("<li><a id='"+bId+"' href='#'>");
						}
						result.append(child.get("block_name"));
						result.append("</a></li>");
					}
					result.append("</ul></li>");
				}else{
					result.append("</li>");
				}
			}
		}
		result.append("</ul>");
		return result.toString();
	}
	
	/**
	 * 取论坛版块
	 * @return
	 */
	private void getForumBlocks(){
		JSONArray roots=CommonDAO.getList(SqlMgr.getSql("GET_FORUM_ROOT_BLOCK"));
		this.setSessionAttr("rootBlocks", roots.toString());
		
		JSONObject chObj=new JSONObject();
		for(int i=0;i<roots.size();i++){
			JSONObject obj=roots.getJSONObject(i);
			String bId=obj.getString("block_id");
			JSONArray children=CommonDAO.getList(SqlMgr.getSql("GET_FORUM_CHILD_BLOCK"),bId);
			chObj.put(bId, children.toString());
		}
		this.setSessionAttr("cBlockMap", chObj.toString());
	}
	
	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public String getPostTitle() {
		return postTitle;
	}

	public void setPostTitle(String postTitle) {
		this.postTitle = postTitle;
	}

	public int getPostType() {
		return postType;
	}

	public void setPostType(int postType) {
		this.postType = postType;
	}

	public String getPostId() {
		return postId;
	}

	public void setPostId(String postId) {
		this.postId = postId;
	}

	public String getParentId() {
		return parentId;
	}

	public void setParentId(String parentId) {
		this.parentId = parentId;
	}

	public int getPageIndex() {
		return pageIndex;
	}

	public void setPageIndex(int pageIndex) {
		this.pageIndex = pageIndex;
	}

	public int getTotalPages() {
		return totalPages;
	}

	public void setTotalPages(int totalPages) {
		this.totalPages = totalPages;
	}

	public String getBlockId() {
		return blockId;
	}

	public void setBlockId(String blockId) {
		this.blockId = blockId;
	}
}